/**
 * Created by John on 2016/7/15.
 */
var MongoClient = require('mongodb').MongoClient;
var mongo = new MongoClient();
var myDB = null;

mongo.connect('mongodb://localhost/', function (err, db) {
    myDB = db.db('BeginningMongoDB');
    myDB.collection('word_stats', function (err, collection) {
        console.log('Before Upserting:');
        showDocs(collection, addUpsert);
    });
});

function showDocs(collection, callback) {
    var query = {word: {$in: ['righty']}};
    collection.find(query, function (err, items) {
        items.toArray(function (err, items) {
            for (var i = 0; i < items.length; i++) {
                console.log(items[i]);
            }
            callback(collection);
        });
    });
}

function addUpsert(collection) {
    var query = {word: 'righty'};
    var update = {
        $set: {
            word: 'righty',
            first: 'r',
            last: 'y', size: 4,
            stats: {vowels: 1, consonants: 4},
            letters: ['r', 'i', 'g', 'h'],
            charsets: [
                {type: 'consonants', chars: ['r', 'g', 'h']},
                {type: 'vowels', chars: ['i']}
            ],
            category: 'New'
        }
    };

    var options = {w: 1, wtimeout: 5 * 1000, journal: true, fsync: false, upsert: true, multi: false};

    collection.update(query, update, options, function (err, items) {
        console.log();
        console.log('Updating as insert results:');
        console.log(items ? items.result : items);
        console.log();
        console.log('After Updating as insert:');
        showDocs(collection, updateUpsert);
    });
}

function updateUpsert(collection) {
    var query = {word: 'righty'};
    var update = {
        $set: {
            word: 'righty',
            first: 'r',
            last: 'y', size: 6,
            stats: {vowels: 1, consonants: 5},
            letters: ['r', 'i', 'g', 'h','t','y'],
            charsets: [
                {type: 'consonants', chars: ['r', 'g', 'h','t','y']},
                {type: 'vowels', chars: ['i']}
            ],
            category: 'Updated'
        }
    };

    var options = {w: 1, wtimeout: 5 * 1000, journal: true, fsync: false, upsert: true, multi: false};

    collection.update(query, update, options, function (err, items) {
        console.log();
        console.log('Updating as insert results:');
        console.log(items ? items.result : items);
        console.log();
        console.log('After Updating as insert:');
        showDocs(collection, close);
    });
}

function close() {
    setTimeout(function () {
        myDB.close();
    }, 3000);
}